var omusic_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.omusic.");

//Popup menu code
function omusic_contextPopupShowing() //Process Context Menu Content
{
    var mitem = document.getElementById('omusic-playthis');
    if(!gContextMenu.onLink)
    {
	if(omusic_controller.mode=='list')
	{
	    mitem.setAttribute('label', getString("rmplaying"));
	}
	else
	{
	    mitem.setAttribute('label', getString("adplaying"));
	}
    }
    else
    {
	if(omusic_controller.mode=='list')
	{
	    mitem.setAttribute('label',getString("adnplay"));
	}
	else
	{
	    mitem.setAttribute('label', getString("playit"));
	}
    }
    gContextMenu.showItem("omusic-playthis", true);
}

function omusic_menuPopupShowing() //Process Main Menu Content
{
    var menumode = document.getElementById('omusic-menu-mode');
    var menudeladdlist = document.getElementById('omusic-menu-deladdlist');
    var menushuffle = document.getElementById('omusic-menu-shuffle');
    var menuenable = document.getElementById('omusic-menu-enable');
    
    var omusicenable = omusic_prefs.getBoolPref("enabled");
    
    if(omusicenable)
    {
	menuenable.setAttribute('label', getString("disableomusic"));
    }
    else
    {
	menuenable.setAttribute('label', getString("enableomusic"));
    }	    	     
    
    if(omusic_controller.mode=='list')
    {
	menumode.setAttribute('label', getString("tofile"));
	menudeladdlist.setAttribute('label', getString("rmlist"));
	menushuffle.setAttribute('hidden', "false");
	var chd = omusic_controller.getPlayer().GetVariable('shuffle');
	menushuffle.setAttribute('checked', chd);
    }
    else
    {
	menumode.setAttribute('label', getString("tolist"));
	menudeladdlist.setAttribute('label', getString("adlist"));
	menushuffle.setAttribute('hidden', "true");
    }
}

function omusic_repeatPopupShowing()
{
    var mod = omusic_controller.getPlayer().GetVariable('repeat');
    if(mod == 'true')document.getElementById('omusic-repeat-t').setAttribute('checked', 'true');
    if(mod == 'false')document.getElementById('omusic-repeat-f').setAttribute('checked', 'true');
    if(mod == 'list')document.getElementById('omusic-repeat-l').setAttribute('checked', 'true');
}

function omusic_songPopupShowing() //Process Song Choose Menu Content
{
    //clear, enum and add
    
    var menu = document.getElementById('omusic-menu-song-chooser');
    //Clear Menu
    while(menu.hasChildNodes())menu.removeChild(menu.firstChild);
    
    //enmu and add
    var doc = omusic_list.getList();
    var tracks = doc.getElementsByTagName('track');
    var len = tracks.length;

    for(var n=0; n<len; n++)
    {
	var tr = document.createElement('menuitem');
	var txt = n+ ': ' + tracks[n].firstChild.firstChild.nodeValue;
	tr.setAttribute('label', txt);
	tr.setAttribute('type', 'radio');
	tr.setAttribute('crop', 'center');
	tr.setAttribute('oncommand', 'omusic_jumpto('+n+');');
	menu.appendChild(tr);
    }
    if(omusic_controller.mode == 'list')
    {
	menu.childNodes[omusic_controller.item].setAttribute('checked', 'true');
    }
}

function omusic_tippopupShowing()
{
    var des = document.getElementById('omusic-title');
    des.setAttribute('value', omusic_controller.title);
    
    var des =document.getElementById('omusic-file');
    des.setAttribute('crop', 'center');
    des.setAttribute('value', omusic_controller.file);
    
    var des =document.getElementById('omusic-item');
    des.setAttribute('value', omusic_controller.item);

    var mm = Math.floor(Math.round(omusic_controller.time)/60);
    var ss = Math.abs(Math.round(omusic_controller.time)%60);

    var des =document.getElementById('omusic-time');
    des.setAttribute('value', mm+':'+ss);

    var des =document.getElementById('omusic-mode');
    des.setAttribute('value', omusic_controller.mode);
    
    var des =document.getElementById('omusic-state');
    des.setAttribute('value', omusic_controller.state);
    
    omusic_update = true;
}

function omusic_tippopupHiding()
{
    omusic_update = false;
}

//Menu items code
function omusic_jumpto(num)
{
    if(omusic_controller.mode != 'list')
    {
	omusic_loadList();
    }
    setTimeout("omusic_controller.playItem("+num+");", omusic_delay);
}

function omusic_repeat(mod)
{
    var chd = omusic_controller.getPlayer().GetVariable('shuffle');
    omusic_controller.getPlayer().setAttribute("flashvars", "height=20&enablejs=true&showdigits=true&repeat="+mod+"&shuffle="+(chd=='true'));
    omusic_reset();
}

function omusic_shuffle()
{
    var chd = omusic_controller.getPlayer().GetVariable('shuffle');
    var chr = omusic_controller.getPlayer().GetVariable('repeat');
    omusic_controller.getPlayer().setAttribute("flashvars", "height=20&enablejs=true&showdigits=true&repeat="+chr+"&shuffle="+!(chd=='true'));
    omusic_reset();
}

function omusic_reset() //reset player menuitem
{
    var opp = document.getElementById('omusic-player');
    var oaa = opp.parentNode;
    var odd = opp.cloneNode('false');
    oaa.removeChild(opp);
    oaa.appendChild(odd);
    omusic_initOverlay();
    omusic_lyrics.updateDisplay('clear');
}

function omusic_modechange() //mode menuitem
{
    if(omusic_controller.mode == 'list') // to file mode, load file, play
    {
	omusic_controller.loadFile(omusic_controller.file, omusic_controller.title);
	omusic_controller.mode = 'file';
    }
    else // to list mode, load list, play
    {
	omusic_loadList();
    }
    setTimeout("omusic_controller.playPause();", omusic_delay);
}

function omusic_fromtolist() //add-remove menu item
{
    if(omusic_controller.mode == 'list') // remove from list, reload, (no-)jump and play
    {
	var omusic_item_num = Math.round(omusic_controller.item);
	omusic_list.deleteFromList(omusic_item_num);
	//load list
	var doc = omusic_list.getList();
	var tracks = doc.getElementsByTagName('track');
	var len = tracks.length;
	if(len>0) //loaded
	{
	    omusic_controller.loadFile(omusic_list.getListPath());
	    if(omusic_item_num < len) //jump & play
		setTimeout("omusic_controller.playItem("+omusic_item_num+");", omusic_delay);
	    else  //no-jump and play
		setTimeout("omusic_controller.playPause();", omusic_delay);
	}
	else //not loaded
	{
	    omusic_controller.loadFile('song.mp3', 'song');
	    omusic_controller.mode = 'file';
	}
    }
    else // add to list
    {
	omusic_list.addToList(omusic_controller.file, omusic_controller.title);
	omusic_list.setOffset(0, omusic_lyrics.delay);
    }
}

function omusic_editTitle()
{
    var new_title = prompt(getString('chtitle'), omusic_controller.title);
    if(new_title && new_title != '')
    {
	omusic_controller.title = new_title;
	updateLyrics(omusic_controller);
	if(omusic_controller.mode == 'list')
	{
	    var doc = omusic_list.getList();
	    var tracks = doc.getElementsByTagName('track');
	    var len = tracks.length;
	    if(len > 0)
	    {
		tracks[omusic_controller.item].firstChild.firstChild.nodeValue = omusic_controller.title;
		omusic_list.putList(doc);
	    }
	}
    }
}

function omusic_searchLyrics()
{
    if(content.document.location.href.indexOf('about:blank') == -1)
    {
	var tab = gBrowser.addTab('');
	gBrowser.selectedTab = tab;
    }
    document.getElementById('urlbar').value = 
	"http://mp3.baidu.com/m?f=ms&tn=baidump3lyric&ct=150994944&lf=2&rn=10&word="+ omusic_controller.title +"&lm=-1";
    handleURLBarCommand();
}

function omusic_viewLyrics()
{
    if(content.document.location.href.indexOf('about:blank') == -1)
    {
	var tab = gBrowser.addTab('');
	gBrowser.selectedTab = tab;
    }
    document.getElementById('urlbar').value = omusic_lyrics.lyricsAddr;
    handleURLBarCommand();	
}

function omusic_setDelay()
{
    var n_delay = prompt(getString('setdelay'), omusic_lyrics.delay);
    if(n_delay && n_delay != '')
    {
	var xx = Math.round(n_delay);
	omusic_lyrics.setDelay(xx);
	if(omusic_controller.mode == 'list')
	{
	    var off = omusic_lyrics.delay;
	    omusic_list.setOffset(omusic_controller.item, off);
	}	
    }
}

function omusic_modDelay(op)
{
    if(op == 1)omusic_lyrics.incDelay();
    else omusic_lyrics.decDelay();
    if(omusic_controller.mode == 'list')
    {
	var off = omusic_lyrics.delay;
	omusic_list.setOffset(omusic_controller.item, off);
    }	
}

function omusic_downloadFile()
{
    if(content.document.location.href.indexOf('about:blank') == -1)
    {
	gBrowser.addTab(omusic_controller.file);
    }
    else
    {
	gBrowser.loadURI(omusic_controller.file);
    }
}

function omusic_openFile()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, getString("openfile"), nsIFilePicker.modeOpen);
    fp.appendFilter("MP3 File", "*.mp3"); 
    fp.appendFilters(nsIFilePicker.filterAll);
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK)
    {
  	var path = FileIO.path(fp.file);
	var name = fp.file.leafName.replace(/\.mp3/, '');
  	omusic_controller.loadFile(path, name);
  	omusic_controller.mode = 'file';
  	setTimeout("omusic_controller.playPause();", omusic_delay);
    }
}

function omusic_listDirMp3(directory)
{
    var files = directory.directoryEntries.QueryInterface(Components.interfaces.nsIDirectoryEnumerator)
    var filelist = [];
    while(files.hasMoreElements())
    {
	var file = files.nextFile;
	if(file.isFile() && file.fileSize != 0 && file.leafName.match(/\.mp3$/))
	{
	    filelist.push(file);
	}
	else if(file.isDirectory())
	{
	    filelist = filelist.concat(omusic_listDirMp3(file));
	}
    }

    return filelist;
}

function omusic_openDir()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, getString("opendir"), nsIFilePicker.modeGetFolder);
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK)
    {
	var directory = fp.file;
	var filelist = omusic_listDirMp3(directory);
	for(var i = 0; i < filelist.length; i ++)
	{
	    var name = filelist[i].leafName.replace(/\.mp3/, '');
	    var path = FileIO.path(filelist[i]);
	    omusic_list.addToList(path, name);
	}
	omusic_loadList();
  	omusic_controller.mode = 'list';
  	setTimeout("omusic_controller.playPause();", omusic_delay);
	
    }
}

function omusic_exportList()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, getString("exportlist"), nsIFilePicker.modeSave);
    fp.appendFilters(nsIFilePicker.filterXML);
    fp.defaultString = 'playlist';
    fp.defaultExtension = 'xml';
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace)
    {
  	var path = fp.file.path;
  	omusic_list.putList(omusic_list.getList(), path);
    }
}

function omusic_mergeList()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, getString("mergelist"), nsIFilePicker.modeOpen);
    fp.appendFilters(nsIFilePicker.filterXML|nsIFilePicker.filterAll);
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK)
    {
  	var path = fp.file.path;
  	var doc = omusic_list.getList(path);
  	omusic_list.mergeList(doc);
  	omusic_loadList();
    }
}

function omusic_replaceList()
{
    const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, getString("replacelist"), nsIFilePicker.modeOpen);
    fp.appendFilters(nsIFilePicker.filterXML|nsIFilePicker.filterAll);
    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK)
    {
  	var path = fp.file.path;
  	omusic_list.putList(omusic_list.getList(path));
  	omusic_loadList();
    }
}

function omusic_clearList()
{
    if(confirm(getString('cllist')))
    {
	omusic_list.createList();
	if(omusic_controller.mode == 'list')omusic_loadList();
    }
}

function omusic_show()
{
    var enable = omusic_prefs.getBoolPref('enabled');
    var lyrics = document.getElementById('oplayer-panel');
    var player = document.getElementById('oplayer-panel-player');

    if(enable)
    {
	lyrics.setAttribute('hidden', false);
	player.setAttribute('hidden', false);
    }
    else
    {
	lyrics.setAttribute('hidden', true);
	player.setAttribute('hidden', true);
    }
}

function omusic_toggle()
{
    var enable = omusic_prefs.getBoolPref('enabled');
    enable = !enable;
    omusic_prefs.setBoolPref('enabled', enable);
    omusic_show();
    if(enable)omusic_reset();
}

function onMenuPlayitSelected(linkURL)
{
    var file_title = gContextMenu.target.textContent;
    var omusic_item_num = Math.round(omusic_controller.item);
    if(gContextMenu.onLink) //add it & play or play
    {
	var linkurl = linkURL; //get url
	if(content.document.location.href.indexOf("mp3.baidu.com")!=-1)
	{
	    var re = /word=\w*,([^,]*),/;
	    var mp3url1 = re.exec(linkURL)[1];
	    if(mp3url1 && mp3url1!='')linkurl = "http://mp3.baidu.com/u?u=" + mp3url1;
	    var flink = gContextMenu.target;
	    while(flink && flink.nodeName!='A')flink = flink.parentNode;
	    var file_author = flink.parentNode.nextSibling.nextSibling.firstChild.textContent;
	    
	    var re2 = /(.*\S)/;
	    var tit = re2.exec(flink.textContent);
	    file_title = tit[1];
	    if(file_author && file_author != '')file_title = file_title + ' - ' + file_author;
	}
	
	if(omusic_controller.mode=='list') //list mode
	{
	    omusic_list.addToList(linkurl, file_title); //to be loaded and played
	}
	else //file mode
	{
	    omusic_controller.loadFile('song.mp3', '');
	    omusic_controller.loadFile(linkurl, file_title); //to be played
	}		
    }
    else //delete now playing or add to list
    {
	if(omusic_controller.mode=='list') //list mode
	{
	    omusic_list.deleteFromList(omusic_item_num); //to be loaded, jumped and played
	}
	else //file mode
	{
	    omusic_list.addToList(omusic_controller.file, omusic_controller.title); //nothing
	    omusic_list.setOffset(0, omusic_lyrics.delay);
	}
    }
    
    if(omusic_controller.mode == 'list') //list mode
    {
	//load list
	var doc = omusic_list.getList();
	var tracks = doc.getElementsByTagName('track');
	var len = tracks.length;
	if(len>0) //loaded
	{
	    omusic_controller.loadFile(omusic_list.getListPath());
	    if(!gContextMenu.onLink && omusic_item_num < len) //jump & play
		setTimeout("omusic_controller.playItem("+omusic_item_num+");", omusic_delay);
	    else  //no-jump and play
		setTimeout("omusic_controller.playItem(0);", omusic_delay);
	}
	else //not loaded
	{
	    omusic_controller.loadFile('song.mp3', 'song');
	    omusic_controller.mode = 'file';
	}
    }
    else //file mode
    {
	if(gContextMenu.onLink) //play
	{
	    setTimeout("omusic_controller.playPause();", omusic_delay);
	}
    }
}

//Flash Player Callback
function getUpdate(typ,pr1,pr2) 
{
    omusic_controller[typ] = Math.round(pr1);
    if(typ=='item')
    {
	omusic_lyrics.setDelay(0);
	if(omusic_controller.mode == 'list')
	{
	    var off = omusic_list.getOffset(Math.round(pr1));
	    omusic_lyrics.setDelay(off);
	}
    }
    if(typ=='time')
    {
	omusic_lyrics.updateDisplay(Math.round(pr1));
	if(omusic_update)omusic_tippopupShowing();
    }
};

function itemData(obj) 
{
    if(obj['title'] != omusic_controller['title'])
    {
	updateLyrics(obj);
	omusic_lyrics.updateDisplay(-Math.round(omusic_lyrics.delay));
    }
    for(var i in obj) 
    { 
	omusic_controller[i] = obj[i];
    }
};

function updateLyrics(obj)
{
    var tt = obj['title'];
    var rr = /([^-]+)(?: - (.*)|$)/;
    var re = rr.exec(tt);
    var ti = re[1];
    var au;
    if(re[2]!=undefined)au=re[2];
    else au='';
    omusic_lyrics.updateDisplay('clear');

    if(obj['file'].match(/^file:\/\/\//))
    {
	var filepath = obj['file'].replace(/file:\/\/\//g, '');
	filepath = filepath.replace(/\//g, DirIO.sep);
	filepath = filepath.replace(/%20/g, ' ');
	omusic_lyrics.localLyrics(ti, au, filepath);
    }
    else
    {
	omusic_lyrics.prepareLyrics(ti, au);
    }
}

//Initialization function
function omusic_initOverlay()
{
    var menu=document.getElementById("contentAreaContextMenu");
    menu.addEventListener("popupshowing", omusic_contextPopupShowing, false);
    omusic_controller.mode="file";
    setTimeout("initPlayer()", omusic_delay);
}

function omusic_loadList()
{
    var doc = omusic_list.getList();
    var tracks = doc.getElementsByTagName('track');
    var len = tracks.length;
    if(len>0) //loaded
    {
	omusic_controller.loadFile(omusic_list.getListPath());
	omusic_controller.mode = 'list';
    }
    else //not loaded
    {
	omusic_controller.loadFile('song.mp3', 'song');
	omusic_controller.mode = 'file';
    }
}

function getString(str)
{
    var strbundle = document.getElementById("omusic-string");
    return strbundle.getString(str);
}

function updateSecurity()
{
    if(navigator.platform.toLowerCase().indexOf('linux') != -1)
    {
	var file = DirIO.get("Home");
	file.append(".macromedia");
	if(!file.exists())DirIO.create(file);
	file.append("Flash_Player");
	if(!file.exists())DirIO.create(file);
	file.append("#Security");
	if(!file.exists())DirIO.create(file);
	file.append("FlashPlayerTrust");
	if(!file.exists())DirIO.create(file);
	file.append("omusic.cfg");
	var trstpath = "chrome://browser/content/browser.xul";
	FileIO.write(file, trstpath, '', 'UTF-8');

    }
    else
    {
	var file = DirIO.get("AppData");
	file.append("Macromedia");
	if(!file.exists())DirIO.create(file);
	file.append("Flash Player");
	if(!file.exists())DirIO.create(file);
	file.append("#Security");
	if(!file.exists())DirIO.create(file);
	file.append("FlashPlayerTrust");
	if(!file.exists())DirIO.create(file);
	file.append("omusic.cfg");
	var instDir = DirIO.get("CurProcD");
	FileIO.write(file, instDir.path, '', 'UTF-8');	
    }
}

function initPlayer()
{
    try
    {
	if(omusic_first)
	{
	    document.getElementById('omusic-player').setAttribute('hidden', 'false');
	    omusic_first = false;
	    omusic_reset();
	}
	else omusic_loadList();
    }
    catch(ee)
    {
	setTimeout("initPlayer()", omusic_delay);
    }
    omusic_show();
}

//Initialization code

var omusic_delay = 100;
var omusic_update = false;
var omusic_controller = new OmusicController();
var omusic_list = new OmusicList();
var omusic_lyrics = new OmusicLyrics();
var omusic_first = true;

updateSecurity();
window.addEventListener("load", omusic_initOverlay, false);
